/**
 * 暂时屏蔽 为了编译整个工程
 */
package labox.innovation.gameserver.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.db.core.L2DatabaseFactory;
import labox.innovation.gameserver.ThreadPoolManager;
import labox.innovation.gameserver.idfactory.IdFactory;
import labox.innovation.gameserver.model.L2Clan;
import labox.innovation.gameserver.model.L2ClanMember;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.network.SystemMessageId;
//import labox.innovation.gameserver.network.serverpackets.ExBrExtraUserInfo;
//import labox.innovation.gameserver.network.serverpackets.PledgeShowInfoUpdate;
//import labox.innovation.gameserver.network.serverpackets.PledgeShowMemberListAll;
//import labox.innovation.gameserver.network.serverpackets.PledgeShowMemberListUpdate;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.gameserver.network.serverpackets.UserInfo;
import labox.innovation.gameserver.timer.Timer;
import labox.innovation.util.Util;

/**
 * This class ...
 *
 * @version $Revision: 1.11.2.5.2.5 $ $Date: 2005/03/27 15:29:18 $
 */
public class ClanTable {

	private static Logger _log = LoggerFactory.getLogger(ClanTable.class.getName());

	private Map<Long, L2Clan> _clans;

	public static ClanTable getInstance() {
		return SingletonHolder._instance;
	}

	public L2Clan[] getClans() {
		return _clans.values().toArray(new L2Clan[_clans.size()]);
	}

	private ClanTable() {
		_clans = new FastMap<Long, L2Clan>();
		L2Clan clan;
//		Connection con = null;
//		try {
//			con = L2DatabaseFactory.getInstance().getConnection();
//			PreparedStatement statement = con.prepareStatement("SELECT clan_id FROM clan_data");
//			ResultSet result = statement.executeQuery();
//
//			// Count the clans
//			int clanCount = 0;
//
//			while (result.next()) {
//				long clanId = result.getLong("clan_id");
//				_clans.put(clanId, new L2Clan(clanId));
//				clan = getClan(clanId);
//				if (clan.getDissolvingExpiryTime() != 0)
//					scheduleRemoveClan(clan.getClanId());
//				clanCount++;
//			}
//			result.close();
//			statement.close();
//
//			_log.info("Restored " + clanCount + " clans from the database.");
//		} catch (Exception e) {
//			_log.error("Error restoring ClanTable.", e);
//		} finally {
//			try {
//				con.close();
//			} catch (Exception e) {
//			}
//		}
//
//		restorewars();
	}

	/**
	 * @param clanId
	 * @return
	 */
	public L2Clan getClan(long clanId) {
		L2Clan clan = _clans.get(Long.valueOf(clanId));
		return clan;
	}

	public L2Clan getClanByName(String clanName) {
		for (L2Clan clan : getClans()) {
			if (clan.getName().equalsIgnoreCase(clanName)) {
				return clan;
			}

		}

		return null;
	}

	/**
	 * Creates a new clan and store clan info to database
	 *
	 * @param player
	 * @return NULL if clan with same name already exists
	 */
	public L2Clan createClan(FuzePcInstance player, String clanName) {
		if (null == player)
			return null;

		if (Config.DEBUG)
			_log.info(player.getObjectId() + "(" + player.getName() + ") requested a clan creation.");

		if (10 > player.getLevel()) {
			player.sendPacket(new SystemMessage(SystemMessageId.YOU_DO_NOT_MEET_CRITERIA_IN_ORDER_TO_CREATE_A_CLAN));
			return null;
		}
		if (0 != player.getClanId()) {
			player.sendPacket(new SystemMessage(SystemMessageId.FAILED_TO_CREATE_CLAN));
			return null;
		}
		if (System.currentTimeMillis() < player.getClanCreateExpiryTime()) {
			player.sendPacket(new SystemMessage(SystemMessageId.YOU_MUST_WAIT_XX_DAYS_BEFORE_CREATING_A_NEW_CLAN));
			return null;
		}
		if (!Util.isAlphaNumeric(clanName) || 2 > clanName.length()) {
			player.sendPacket(new SystemMessage(SystemMessageId.CLAN_NAME_INCORRECT));
			return null;
		}
		if (16 < clanName.length()) {
			player.sendPacket(new SystemMessage(SystemMessageId.CLAN_NAME_TOO_LONG));
			return null;
		}

		if (null != getClanByName(clanName)) {
			// clan name is already taken
			SystemMessage sm = new SystemMessage(SystemMessageId.S1_ALREADY_EXISTS);
			sm.addString(clanName);
			player.sendPacket(sm);
			sm = null;
			return null;
		}

//		L2Clan clan = new L2Clan(IdFactory.getInstance().getNextId(IdFactory.ID_CLAN), clanName);
//		L2ClanMember leader = new L2ClanMember(clan, player.getName(), player.getLevel(), player.getClassId().getId(), player.getObjectId(), player.getPledgeType(), player.getPowerGrade(), player.getTitle(), player.getAppearance().getSex(), player.getBioType().ordinal());
//		clan.setLeader(leader);
//		leader.setPlayerInstance(player);
//		clan.store();
//		player.setClan(clan);
//		player.setPledgeClass(leader.calculatePledgeClass(player));
//		player.setClanPrivileges(L2Clan.CP_ALL);

//		if (Config.DEBUG)
//			_log.info("New clan created: " + clan.getClanId() + " " + clan.getName());
//
//		_clans.put(Long.valueOf(clan.getClanId()), clan);
//
//		//should be update packet only
//		player.sendPacket(new PledgeShowInfoUpdate(clan));
//		player.sendPacket(new PledgeShowMemberListAll(clan, player));
//		player.sendPacket(new UserInfo(player));
//		player.sendPacket(new ExBrExtraUserInfo(player));
//		player.sendPacket(new PledgeShowMemberListUpdate(player));
//		player.sendPacket(new SystemMessage(SystemMessageId.CLAN_CREATED));
//		return clan;
		return null;
	}

	public synchronized void destroyClan(long clanId) {
		L2Clan clan = getClan(clanId);
		if (clan == null) {
			return;
		}

		clan.broadcastToOnlineMembers(new SystemMessage(SystemMessageId.CLAN_HAS_DISPERSED));

		L2ClanMember leaderMember = clan.getLeader();
		if (leaderMember == null)
			clan.getWarehouse().destroyAllItems("ClanRemove", null, null);
		else
			clan.getWarehouse().destroyAllItems("ClanRemove", clan.getLeader().getPlayerInstance(), null);

		for (L2ClanMember member : clan.getMembers()) {
			clan.removeClanMember(member.getObjectId(), 0);
		}

		_clans.remove(clanId);

		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("DELETE FROM clan_data WHERE clan_id=?");
			statement.setLong(1, clanId);
			statement.execute();
			statement.close();

			statement = con.prepareStatement("DELETE FROM clan_privs WHERE clan_id=?");
			statement.setLong(1, clanId);
			statement.execute();
			statement.close();

			statement = con.prepareStatement("DELETE FROM clan_skills WHERE clan_id=?");
			statement.setLong(1, clanId);
			statement.execute();
			statement.close();

			statement = con.prepareStatement("DELETE FROM clan_subpledges WHERE clan_id=?");
			statement.setLong(1, clanId);
			statement.execute();
			statement.close();

			statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? OR clan2=?");
			statement.setLong(1, clanId);
			statement.setLong(2, clanId);
			statement.execute();
			statement.close();

			statement = con.prepareStatement("DELETE FROM clan_notices WHERE clan_id=?");
			statement.setLong(1, clanId);
			statement.execute();
			statement.close();

			if (Config.DEBUG)
				_log.info("clan removed in db: " + clanId);
		} catch (Exception e) {
			_log.error("Error removing clan from DB.", e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
			}
		}
	}

	public void scheduleRemoveClan(final long clanId) {
		int time = (int) Math.max(getClan(clanId).getDissolvingExpiryTime() - System.currentTimeMillis(), 300000);
		Timer t = new Timer(time, false, new Runnable() {
			public void run() {
				if (getClan(clanId) == null) {
					return;
				}
				if (getClan(clanId).getDissolvingExpiryTime() != 0) {
					destroyClan(clanId);
				}
			}
		});
		t.start();
	}

	public boolean isAllyExists(String allyName) {
		for (L2Clan clan : getClans()) {
			if (clan.getAllyName() != null && clan.getAllyName().equalsIgnoreCase(allyName)) {
				return true;
			}
		}
		return false;
	}

	public void storeclanswars(int clanId1, int clanId2) {
		L2Clan clan1 = ClanTable.getInstance().getClan(clanId1);
		L2Clan clan2 = ClanTable.getInstance().getClan(clanId2);
		clan1.setEnemyClan(clan2);
		clan2.setAttackerClan(clan1);
		clan1.broadcastClanStatus();
		clan2.broadcastClanStatus();
		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement("REPLACE INTO clan_wars (clan1, clan2, wantspeace1, wantspeace2) VALUES(?,?,?,?)");
			statement.setInt(1, clanId1);
			statement.setInt(2, clanId2);
			statement.setInt(3, 0);
			statement.setInt(4, 0);
			statement.execute();
			statement.close();
		} catch (Exception e) {
			_log.error("Error storing clan wars data.", e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
			}
		}
		//SystemMessage msg = new SystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_BEGUN);
		//
		SystemMessage msg = new SystemMessage(SystemMessageId.CLAN_WAR_DECLARED_AGAINST_S1_IF_KILLED_LOSE_LOW_EXP);
		msg.addString(clan2.getName());
		clan1.broadcastToOnlineMembers(msg);
		//msg = new SystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_BEGUN);
		//msg.addString(clan1.getName());
		//clan2.broadcastToOnlineMembers(msg);
		// clan1 declared clan war.
		msg = new SystemMessage(SystemMessageId.CLAN_S1_DECLARED_WAR);
		msg.addString(clan1.getName());
		clan2.broadcastToOnlineMembers(msg);
	}

	public void deleteclanswars(long clanId1, long clanId2) {
		L2Clan clan1 = ClanTable.getInstance().getClan(clanId1);
		L2Clan clan2 = ClanTable.getInstance().getClan(clanId2);
		clan1.deleteEnemyClan(clan2);
		clan2.deleteAttackerClan(clan1);
		clan1.broadcastClanStatus();
		clan2.broadcastClanStatus();
		//for(L2ClanMember player: clan1.getMembers())
		//{
		//	if(player.getPlayerInstance()!=null)
		//			player.getPlayerInstance().setWantsPeace(0);
		//}
		//for(L2ClanMember player: clan2.getMembers())
		//{
		//	if(player.getPlayerInstance()!=null)
		//			player.getPlayerInstance().setWantsPeace(0);
		//}
		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?");
			statement.setLong(1, clanId1);
			statement.setLong(2, clanId2);
			statement.execute();
			//statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?");
			//statement.setInt(1,clanId2);
			//statement.setInt(2,clanId1);
			//statement.execute();

			statement.close();
		} catch (Exception e) {
			_log.error("Error removing clan wars data.", e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
			}
		}
		//SystemMessage msg = new SystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_ENDED);
		SystemMessage msg = new SystemMessage(SystemMessageId.WAR_AGAINST_S1_HAS_STOPPED);
		msg.addString(clan2.getName());
		clan1.broadcastToOnlineMembers(msg);
		msg = new SystemMessage(SystemMessageId.CLAN_S1_HAS_DECIDED_TO_STOP);
		msg.addString(clan1.getName());
		clan2.broadcastToOnlineMembers(msg);
		//msg = new SystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_ENDED);
		//msg.addString(clan1.getName());
		//clan2.broadcastToOnlineMembers(msg);
	}

	public void checkSurrender(L2Clan clan1, L2Clan clan2) {
		int count = 0;
//		for (L2ClanMember player : clan1.getMembers()) {
//			if (player != null && player.getPlayerInstance().getWantsPeace() == 1)
//				count++;
//		}
		if (count == clan1.getMembers().length - 1) {
			clan1.deleteEnemyClan(clan2);
			clan2.deleteEnemyClan(clan1);
			deleteclanswars(clan1.getClanId(), clan2.getClanId());
		}
	}

	private void restorewars() {
//		Connection con = null;
//		try {
//			con = L2DatabaseFactory.getInstance().getConnection();
//			PreparedStatement statement;
//			statement = con.prepareStatement("SELECT clan1, clan2, wantspeace1, wantspeace2 FROM clan_wars");
//			ResultSet rset = statement.executeQuery();
//			while (rset.next()) {
//				getClan(rset.getLong("clan1")).setEnemyClan(rset.getLong("clan2"));
//				getClan(rset.getLong("clan2")).setAttackerClan(rset.getLong("clan1"));
//			}
//			statement.close();
//		} catch (Exception e) {
//			_log.error("Error restoring clan wars data.", e);
//		} finally {
//			try {
//				con.close();
//			} catch (Exception e) {
//			}
//		}
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final ClanTable _instance = new ClanTable();
	}
}
